//
//  WKStatusPictureView.swift
//  WKWeibo
//
//  Created by 恋guang年 on 16/3/31.
//  Copyright © 2016年 恋guang年. All rights reserved.
//
import SnapKit
import UIKit
import SDWebImage

class WKStatusPictureView: UICollectionView {
    private let ID = "WKStatusPictureCell"
    //要显示图片URL数组
    var imageURLs:[NSURL]?
    {
        didSet{
            //拿到图片URL数组 更新View大小
            let viewSize = calculateViwSize()
            //更新View大小
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(viewSize)
            }
                self.reloadData()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //布局属性
    private let layout = UICollectionViewFlowLayout()
    
    init(){
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        //设置数据源
        self.dataSource = self
        //注册cell 
        self.registerClass(WKStatusPictureCell.self, forCellWithReuseIdentifier:ID)
        backgroundColor = UIColor.clearColor()
    }
    //    根据传入的URL数组确定pictureView的大小
    func calculateViwSize() -> CGSize {
        //确定layout的一些约束
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
//        如果没有图片 返回CGSizeZero
        let count = imageURLs?.count ?? 0
        if imageURLs?.count == 0 {
            layout.itemSize = CGSizeZero
            return CGSizeZero
        }
        
        // 当调用这个地方的时候,cell是即将显示,图片是已经缓存完成了的
        // 单图会按照图片 原始尺寸 显示
        if imageURLs?.count == 1{
            //默认图片大小
            layout.itemSize = CGSizeMake(WKStatusPictureItemSizeHW, WKStatusPictureItemSizeHW)
            //获得图片的绝对路径
            if  let urlString = imageURLs?[0].absoluteString{
                //从sd缓存中加载图片 或的图片原始尺寸
                layout.itemSize = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(urlString).size
            }
       
            return layout.itemSize
        }
        ///多张图片 4张和两张的时候是2列 其它是3列
        layout.minimumInteritemSpacing = WKStatusPictureMargin
        layout.minimumLineSpacing = WKStatusPictureMargin
        //默认是3列
        var column = WKStatusPictureMaxColumn
        //4张和两张的时候是2列
        if imageURLs?.count == 4 || imageURLs?.count == 2 {
            column = 2
        }
        layout.itemSize = CGSize(width: WKStatusPictureItemSizeHW, height: WKStatusPictureItemSizeHW)
        //行数 固定算法
        let row = (count + column - 1) / column
        //配图视图的宽 = item的宽*列数 + (列数-1)*item之间的间距
        let width = WKStatusPictureItemSizeHW * CGFloat(column) + WKStatusPictureMargin * (CGFloat(column) - 1)
        //配图视图的高 = item的高*行数 + (行数 - 1)*item之间的上下间距
        let height = WKStatusPictureItemSizeHW * CGFloat(row) + WKStatusPictureMargin * CGFloat(row-1)
        
        return CGSize(width: width, height: height)
    }


}
//MARK: - 数据源
extension WKStatusPictureView : UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ??  0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ID, forIndexPath:indexPath) as! WKStatusPictureCell
        cell.imageURL = imageURLs?[indexPath.row]
        cell.backgroundColor = UIColor.randomColor()
        return cell
    }
}
//MARK : - 自定义cell
class WKStatusPictureCell:UICollectionViewCell{
    //图片URL
    var imageURL:NSURL?{
        didSet{
            if let url = imageURL {
                iconView.sd_setImageWithURL(url, placeholderImage:nil, options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.LowPriority])
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加iconVeiw和约束
        prepareForUI()
    }
    ///  添加子控件和约束
    func prepareForUI(){
        contentView.addSubview(iconView)
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    //每个cell添加一个iconView
    private lazy var iconView:UIImageView = {
       let iconView1 = UIImageView()
        iconView1.contentMode = UIViewContentMode.ScaleAspectFill
        iconView1.clipsToBounds = true
        return iconView1
    }()
}













